import numpy as np
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from django.contrib.auth.models import User
from FerpaApp import models

def RadarGraph(itemLabel,itemStat,itemTitle):
    # 雷达图数据（归一化到0-1）
    # radar_labels = np.array(itemLabel)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    radar_labels = itemLabel
    radar_stats = np.array(itemStat)
    radar_stats = radar_stats / np.max(radar_stats)
    # 角度
    angles = np.linspace(0, 2 * np.pi, len(radar_labels), endpoint=False)
    # 创建画布和极坐标子图
    fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': 'polar'})
    # 绘制雷达图（多边形）
    ax.fill(angles, radar_stats, color='b', alpha=0.25)
    ax.plot(angles, radar_stats, color='b')
    # 设置角度刻度标签
    ax.set_xticks(angles)
    ax.set_xticklabels(radar_labels)
    # 显示网格线（可选）
    ax.grid(True)
    # 显示图形
    return fig
def PieGraph(ItemSize, ItemLabels, ItemColors, ItemTitle):
    sizes = ItemSize
    labels = ItemLabels
    colors = ItemColors
    plt.rcParams['font.sans-serif'] = ['SimHei']
    fig, ax = plt.subplots(figsize=(6, 6))
    ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140, colors=colors,
            wedgeprops=dict(edgecolor='white', linewidth=2),  # 使用白色边框，增加线宽
            textprops={'fontsize': 12, 'color': 'black', 'weight': 'bold'})  # 文本加粗并设置为黑色
    ax.axis('equal')  # 保持饼图为圆形
    fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)  # 调整子图参数以去除多余空白
    # 设置标题
    ax.set_title(ItemTitle, fontweight='bold', color="blue")
    return fig
def PieByteImg(ItemSize , ItemLabels, ItemColors, ItemTitle):
    #载入数据
    size = ItemSize
    labels = ItemLabels
    colors = ItemColors
    title = ItemTitle

    fig = PieGraph(size,labels,colors,title)
    imgPie = BytesIO()
    fig.savefig(imgPie, format="PNG")
    imgPie.seek(0)

    ImgPie64 = base64.b64encode(imgPie.getvalue()).decode('utf-8')

    return ImgPie64
def RadarByteImg(Itemsize, ItemLabels, ItemTitle):
    size = Itemsize
    labels = ItemLabels
    title = ItemTitle
    fig = RadarGraph(itemStat=size, itemLabel=labels, itemTitle=title)
    ImgRadar = BytesIO()
    fig.savefig(ImgRadar, format="PNG")
    ImgRadar.seek(0)
    ImgRadar64 = base64.b64encode(ImgRadar.getvalue()).decode('utf-8')
    return ImgRadar64
def ConformityGraph(username):
    userItem = User.objects.get(username=username)
    userdata = userItem.AnalyseData.all()

    GraphLog = {}
    for _ in userdata:
        id = _.id
        name = _.name
        radar_data = _.radar_data
        radar_labels = _.radar_labels
        pie_data = _.pie_data
        pie_labels = _.pie_labels
        pie_color = ['blue' for i in range(len(pie_data))]
        radarGraph = RadarByteImg(Itemsize=radar_data, ItemLabels=radar_labels ,ItemTitle=name)
        pieGraph = PieByteImg(ItemSize=pie_data, ItemLabels=pie_labels, ItemColors=pie_color, ItemTitle=name)
        GraphLog[name] = {'id': id,
                          'name': name,
                          'radarGraph': radarGraph,
                          'pieGraph': pieGraph}
    first_name = userdata[0].name

    return GraphLog, first_name